﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.View == "undefined") Axis.View = {};
if (typeof Axis.View.Project == "undefined") Axis.View.Project = {};
Axis.View.Project.Questionare = {
    IndexQues: 0,
    InputValue: '',
    CurrSentence: 0,
    Path: [],
    CurrentZOrder: -1,
    PathResult: [],
    FinishedQuestion: [],
    BackQuestion: function (opt) {
        var thisObj = this;
        $(".question").hide();
        var i = 1;
        for (; i < thisObj.Path.length; i++)
            if (thisObj.CurrSentence == thisObj.Path[i].ID) {
                thisObj.CurrSentence = thisObj.Path[i - 1].ID;
                break;
            }
        if (i == 1)
            $("#btnBackQuestion").hide();
        $("#question_" + thisObj.CurrSentence).show();
        thisObj.CurrentZOrder = $("#question_" + thisObj.CurrSentence).attr('zorder');
    },
    IsEmptyAnswer: function () {
        var thisObj = Axis.View.Project.Questionare;
        var questionType = parseInt($("#question_" + thisObj.CurrSentence).attr('type'));
        var question = thisObj.CurrSentence;
        var ResponseValue = '';
        switch (questionType) {
            case 0: //SA
            case 2: //True/False
            case 4: //Scale
                $.each($($.string.Format('input:radio[question="{0}"]:checked', question)), function (index, item) {
                    ResponseValue += $(this).val() + ',';
                });
                return ResponseValue.length == 0;
            case 1: //Checkbox
            case 7:
            case 6:
                $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                    ResponseValue += $(this).val() + ',';
                });
                return ResponseValue.length == 0;
            case 3: //Textbox 
                ResponseText = $.trim($("#txtOption" + question).val());
                return ResponseText.length == 0;

        }
        return false;
    },
    IsLogicAnswer: function () {
        var thisObj = Axis.View.Project.Questionare;
        var questionType = parseInt($("#question_" + thisObj.CurrSentence).attr('type'));
        var question = thisObj.CurrSentence;
        var ResponseValue = '';

        switch (questionType) {
            case 1: //Checkbox
            case 7: //Checkbox
                var isAllowText = true;

                var numResponse = 0;
                var arrOptionExclusion = new Array();
                $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                    ResponseValue += $(this).val() + ',';
                    numResponse++;
                    var ResponseText = $(this).attr('text');
                    if (typeof $(this).attr('AllowInput') != 'undefined')
                        if ($(this).attr('AllowInput') == "1") {
                            var ResID = $(this).attr('qvalue');
                            ResponseText = $($.string.Format("#txt_chk_{0}_{1}", ResID, question)).val();
                            if ($.trim(ResponseText).length == 0) {
                                $.CAlert.Alert({
                                    Title: "Thông báo",
                                    Content: $.string.Format('Vui lòng ghi rõ thông tin', 1)
                                });
                                isAllowText = false;

                            }
                        }

                    if (typeof $(this).attr('exclusion') != 'undefined')
                        if ($(this).attr('exclusion') == "1") {
                            arrOptionExclusion.push(" " + $(this).attr('text'));
                        }
                });
                if (isAllowText == false)
                    return false;
                if ((arrOptionExclusion.length > 0 && arrOptionExclusion.length != numResponse) || (arrOptionExclusion.length > 1)) {
                    $.CAlert.Alert({
                        Title: "Thông báo",
                        Content: $.string.Format('Đã chọn một trong các yếu tố({0}) thì không được chọn các yếu tố khác', arrOptionExclusion.toString())
                    });
                    return false;
                }

                break;
            case 6:
                var isAllowText = true;
                var count = 0;
                $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                    ResponseValue += $(this).val() + ',';
                    count++;
                });
                var maxresponsecount = parseInt($("#question_" + question).attr('maxresponsecount'));

                //maxresponsecount
                if (count == 0)
                    return false;
                if (maxresponsecount < count) {
                    $.CAlert.Alert({
                        Title: "Thông báo",
                        Content: $.string.Format('Bạn đã trả lời quá {0} lựa chọn', maxresponsecount)
                    });
                    return false;
                }
                break;
            case 8:
                var total = 0;
                $.each($($.string.Format('input[question="{0}"]', question)), function (index, item) {
                    if ($.trim($(this).val()).length > 0)
                        if (!isNaN($(this).val()))
                            total += parseInt($(this).val());
                });
                var maxresponsecount = parseInt($("#question_" + question).attr('maxresponsecount'));
                if (maxresponsecount != total) {
                    $.CAlert.Alert({
                        Title: "Thông báo",
                        Content: $.string.Format('Tổng giá trị của bạn phải bằng={0}', maxresponsecount)
                    });
                    return false;
                }
                break;
            case 0:
                var isAllowText = true;
                $.each($($.string.Format('input:radio[question="{0}"]:checked', question)), function (index, item) {
                    ResponseValue += $(this).val() + ',';
                    var ResponseText = $(this).attr('text');
                    if (typeof $(this).attr('AllowInput') != 'undefined')
                        if ($(this).attr('AllowInput') == "1") {
                            var ResID = $(this).attr('qvalue');
                            ResponseText = $($.string.Format("#txt_rad_{0}", ResID)).val();
                            if ($.trim(ResponseText).length == 0) {
                                $.CAlert.Alert({
                                    Title: "Thông báo",
                                    Content: $.string.Format('Vui lòng ghi rõ thông tin', 1)
                                });
                                isAllowText = false;

                            }
                        }
                });

                if (isAllowText == false)
                    return false;
                break;
            case 5:
            case 10:
                var numQues = parseInt($("#question_" + question).attr('numrow'));
                if ($($.string.Format('input:radio[matrix="{0}"]:checked', question)).length < numQues) {
                    $.CAlert.Alert({
                        Title: "Thông báo",
                        Content: $.string.Format('Bạn chưa check đủ {0} câu cần thiết.', numQues)
                    });
                    return false;
                }
                break;



        }
        return true;
    },
    ResultFinishedQuestion: function () {
        var thisObj = this;
        var pattern = '<R QID="{0}" V="{1}" T="{2}"/>';
        var dataPost = '';
        var endPath = true;

        $.each($(".question"), function (index, item) {
            var question = $(item).attr('question');
            var questionType = parseInt($(item).attr('type'));
            var ResponseValue = "";
            if (thisObj.Path.length > 0) {
                if (question > thisObj.CurrSentence) {
                    for (var i = 0; i < thisObj.Path.length - 1; i++)
                        if (thisObj.CurrSentence == thisObj.Path[i].ID) {
                            thisObj.CurrSentence = thisObj.Path[i + 1].ID;
                            if (i != thisObj.Path.length - 1)
                                endPath = false;
                            break;
                        }
                    return false;
                }
            }
            switch (questionType) {
                case 0: //SA
                case 2: //True/False
                case 4: //Scale
                    $.each($($.string.Format('input:radio[question="{0}"]:checked', question)), function (index, item) {
                        ResponseValue += $(this).val() + ',';
                    });
                    if (ResponseValue.length > 0)
                        ResponseValue = ResponseValue.substr(0, ResponseValue.length - 1);
                    break;
                case 1: //Checkbox        
                    $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                        ResponseValue += $(this).val() + ',';
                    });
                    if (ResponseValue.length > 0)
                        ResponseValue = ResponseValue.substr(0, ResponseValue.length - 1);
                    break;
            }
            dataPost += $.string.Format(pattern, question, ResponseValue);
        });
        //var pData = '{' + $.string.Format("'input':'{0}'", dataPost) + '}';
        return dataPost;
        var pattern = '<R QID="{0}" V="{1}" T="{2}"/>';
        var dataPost = thisObj.InputValue;
        var endPath = true;


        // SetRulerPercent(Math.round((parseFloat(thisObj.IndexQues + '') / QuestionCount) * 100));
        $.each($(".question"), function (index, item) {
            //            if (thisObj.Path.length == 6)
            //                debugger;
            var question = $(item).attr('question');
            var zorder = parseInt($(item).attr('zorder'));
            var questionType = parseInt($(item).attr('type'));
            var ResponseValue = "";
            var ResponseText = "";
            if (thisObj.Path.length > 0) {
                if (zorder > parseInt(thisObj.CurrentZOrder + '')) {
                    for (var i = 0; i < thisObj.Path.length - 1; i++)
                        if (thisObj.CurrSentence == thisObj.Path[i].ID) {
                            thisObj.CurrSentence = thisObj.Path[i + 1].ID;
                            if (i != thisObj.Path.length - 1)
                                endPath = false;
                            break;
                        }
                    return false;
                }
            }
            switch (questionType) {
                case 0: //SA
                case 2: //True/False
                case 4: //Scale
                    $.each($($.string.Format('input:radio[question="{0}"]:checked', question)), function (index, item) {

                        ResponseValue = $(this).val();
                        var ResponseText = $(this).attr('text');
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $($.string.Format("#txt_rad_{0}_{1}", ResID, question)).val();
                            }
                        dataPost += $.string.Format(pattern, question, $.HtmlEncode(ResponseValue), $.HtmlEncode(ResponseText));
                    });
                    break;
                case 1: //Checkbox        
                    $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                        ResponseValue = $(this).val();
                        var ResID = $(this).attr('qvalue');
                        var ResponseText = $(this).attr('text');
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $($.string.Format("#txt_chk_{0}_{1}", ResID, question)).val();

                            }
                        dataPost += $.string.Format(pattern, question, $.HtmlEncode(ResponseValue), $.HtmlEncode(ResponseText));
                    });
                    break;
                case 3: //Textbox 
                    ResponseText = $.string.Format(",ResponseText:'{0}'", $("#txtOption" + question).val());
                    dataPost += $.string.Format(pattern, question, $.HtmlEncode(ResponseValue), $.HtmlEncode(ResponseText));

                    break;
                case 5: //Matrix
                    dataPost += $.string.Format(pattern, question, ResponseValue, ResponseText);
                    break;
                case 10: //Matrix
                    dataPost += $.string.Format(pattern, question, ResponseValue, ResponseText);
                    break;
            }
            // dataPost += $.string.Format(pattern, question, ResponseValue);
        });

        return dataPost;

    },
    CheckMaxMaxResponse: function () {
        var thisObj = Axis.View.Project.Questionare;
        var question = thisObj.CurrSentence;
        var questionType = parseInt($("#question_" + question).attr('type'));
        var maxAnswer = parseInt($("#question_" + question).attr('maxresponsecount'));
        if ((!(questionType == '6' || questionType == '1')) || maxAnswer == 0)
            return true;

        var numAnswer = $($.string.Format('input:checkbox[question="{0}"]:checked', question)).length;
        if (numAnswer > maxAnswer) {

            $.CAlert.Alert({
                Title: "Thông báo",
                Content: $.string.Format('Câu hỏi hiện tại bạn chỉ có thể chọn nhiều nhất {0} phương án trả lời.', maxAnswer)
            }, function () {

            });

            return false;
        }
        return true;
    },
    GetNextQuestion: function () {
        var thisObj = this;
        if (!thisObj.CheckMaxMaxResponse())
            return false;
        var pattern = '<R QID="{0}" V="{1}" T="{2}"/>';
        var dataPost = '';
        var endPath = true;
        var isAllowText = true;
        if (thisObj.IsEmptyAnswer()) {
            $.CAlert.Alert({
                Title: "Thông báo",
                Content: $.string.Format("Bạn chưa chọn phương án trả lời cho câu hỏi này.")
            });
            return false;
        };
        if (!thisObj.IsLogicAnswer()) {
            return false;
        };

        SetRulerPercent(Math.round((parseFloat(thisObj.Path.length + '') * 100 / QuestionCount)));
        $.each($(".question"), function (index, item) {
            //            if (thisObj.Path.length == 6)
            //                debugger;
            var question = $(item).attr('question');
            var zorder = parseInt($(item).attr('zorder'));
            var questionType = parseInt($(item).attr('type'));
            var ResponseValue = "";
            var ResponseText = "";
            if (thisObj.Path.length > 0) {
                if (zorder > parseInt(thisObj.CurrentZOrder + '')) {
                    for (var i = 0; i < thisObj.Path.length - 1; i++)
                        if (thisObj.CurrSentence == thisObj.Path[i].ID) {
                            thisObj.CurrSentence = thisObj.Path[i + 1].ID;
                            if (i != thisObj.Path.length - 1)
                                endPath = false;
                            break;
                        }
                    return false;
                }
            }
            switch (questionType) {
                case 0: //SA
                case 2: //True/False
                case 4: //Scale
                    $.each($($.string.Format('input:radio[question="{0}"]:checked', question)), function (index, item) {

                        ResponseValue = $(this).val();
                        var ResponseText = $(this).attr('text');
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $($.string.Format("#txt_rad_{0}_{1}", ResID, question)).val();
                            }
                        dataPost += $.string.Format(pattern, question, $.HtmlEncode(ResponseValue), $.HtmlEncode(ResponseText));
                    });
                    break;
                case 1: //Checkbox  
                case 7: //Checkbox        
                    $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                        ResponseValue = $(this).val();
                        var ResID = $(this).attr('qvalue');
                        var ResponseText = $(this).attr('text');
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $($.string.Format("#txt_chk_{0}_{1}", ResID, question)).val();
                                if ($.trim(ResponseText).length == 0) {
                                    $.CAlert.Alert({
                                        Title: "Thông báo",
                                        Content: $.string.Format('Vui lòng ghi rõ thông tin', 1)
                                    });
                                    isAllowText = false;

                                }
                            }
                        dataPost += $.string.Format(pattern, question, $.HtmlEncode(ResponseValue), $.HtmlEncode(ResponseText));
                    });

                    break;
                case 6: //Arrangements        
                    $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                        ResponseValue = $(this).val();
                        var ResID = $(this).attr('qvalue');
                        var ResponseText = $(this).attr('Arrangements');
                        dataPost += $.string.Format(pattern, question, $.HtmlEncode(ResponseValue), $.HtmlEncode(ResponseText));
                    });
                    break;
                case 8: //CheckSum
                    $.each($($.string.Format('input[question="{0}"]', question)), function (index, item) {
                        if ($.trim($(this).val()).length > 0)
                            if (!isNaN($(this).val()))
                                dataPost += $.string.Format(pattern, question, $(item).attr("qID"), $(this).val());
                    });
                    break;
                case 3: //Textbox 
                    ResponseText = $.string.Format(",ResponseText:'{0}'", $("#txtOption" + question).val());
                    dataPost += $.string.Format(pattern, question, $.HtmlEncode(ResponseValue), $.HtmlEncode(ResponseText));

                    break;
                case 5: //Matrix
                    dataPost += $.string.Format(pattern, question, ResponseValue, ResponseText);
                    break;
                case 9: //Matrix MA
                    dataPost += $.string.Format(pattern, question, ResponseValue, ResponseText);
                    break;
                case 10: //Matrix Column
                    dataPost += $.string.Format(pattern, question, ResponseValue, ResponseText);
                    break;

            }
            // dataPost += $.string.Format(pattern, question, ResponseValue);
        });

        if (isAllowText == false) return;
        var pData = '{' + $.string.Format("'input':'{0}'", thisObj.InputValue + dataPost) + '}';
        if (thisObj.IndexQues >= 1)
            $("#btnBackQuestion").show();
        var overlay = new COverlay();
        overlay.Init("#QuestionContent");
        $.ajax({
            url: 'Service/ProjectService.asmx/GetNextQuestion',
            type: 'POST',
            data: pData,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                var data = eval("(" + pData.d + ")");
                if (data.length == 0 && thisObj.Path.length == 0) {
                    $.CAlert.Alert({
                        Title: "Thông báo",
                        Content: 'Dự án này chưa sẵn sàng. Chưa có câu hỏi cho dự án này'
                    }, function () {

                    });
                    return;
                }
                if (data.length == 0) {
                    if (ProjectID == 50) {
                        if (thisObj.Path.length < 6) {
                            $.CAlert.Alert({
                                Title: "Thông báo",
                                Content: 'Cám ơn bạn đã tham gia khảo sát. Tuy nhiên bạn không thuộc đối tượng khảo sát. Xin mời bạn tham gia dự án khác.'
                            }, function () {
                                window.location = "ProjectList.aspx";
                            });
                            return;
                        }
                    }
                    if (thisObj.Path.length < 6) {
                        $.CAlert.Alert({
                            Title: "Thông báo",
                            Content: 'Cám ơn bạn đã tham gia khảo sát. Tuy nhiên bạn không thuộc đối tượng khảo sát. Xin mời bạn tham gia dự án khác.'
                        }, function () {
                            window.location = "ProjectList.aspx";
                        });
                    }
                    else {
                        $("#question_" + thisObj.Path.pop().ID).show();
                        thisObj.SaveServey(1);
                        SetRulerPercent(100);
                    }
                    return;
                }
                $("#btnNext").show();
                if (thisObj.CurrSentence != data[0].ID) {
                    if (endPath == false) //da chuyen nhanh khac
                    {
                        //                        $.CAlert.Confirm({
                        //                            Title: "Bạn đang chọn một nhánh khảo sát khác",
                        //                            Content: $.string.Format("Bạn đang chọn một nhánh khảo sát khác. Nếu bạn nhấn ok thì các câu trả lời phía sau sẽ bị xóa trăng.")
                        //                        }, function (isOK) {
                        //                            if (isOK) {
                        var newPath = new Array();
                        thisObj.CurrentZOrder = data[0].ZOrder;
                        for (var i = 0; i < thisObj.Path.length; i++) {
                            var zorder = parseInt($("#question_" + thisObj.Path[i].ID).attr('zorder'));
                            //  console.log(i, thisObj.CurrentZOrder, zorder, (thisObj.CurrentZOrder <= zorder));
                            if (thisObj.CurrentZOrder >= zorder)
                                newPath.push(thisObj.Path[i]);
                            else
                                $("#question_" + thisObj.Path[i].ID).remove();

                        }
                        //  debugger;
                        //console.log(newPath);
                        thisObj.Path = null;
                        thisObj.Path = newPath;
                        thisObj.Path.push(data[0]);
                        thisObj.CurrSentence = data[0].ID;

                        //  console.log('thisObj.CurrentZOrder', thisObj.CurrentZOrder);
                        thisObj.IndexQues = thisObj.CurrentZOrder;
                        var question = $.string.Format('<li id="question_{0}" class="question" question="{0}" type="{3}" ZOrder="{4}" MaxResponseCount="{5}"><span class="project-question-symbol">Q.</span><span class="project-question-content">{1}. {2}</span></li>', data[0].ID, data[0].Code, data[0].QuestionText, data[0].Type, data[0].ZOrder, data[0].MaxResponseCount);

                        if (data[0].ContentType == "2")
                            question += $.string.Format('<div class="enbedYoutube"><embed width="420" height="345" src="{0}" type="application/x-shockwave-flash"></embed></div>', data[0].MediaUrl);
                        $("#listQuestion").append(question);
                        thisObj.GetListOption(data[0]);
                        //                                $("#question_" + data[0].ID).show();
                        //                            }
                        //                        });
                    }
                    else {
                        thisObj.Path.push(data[0]);
                        thisObj.CurrSentence = data[0].ID;
                        //  debugger;
                        thisObj.CurrentZOrder = data[0].ZOrder;
                        thisObj.IndexQues = thisObj.CurrentZOrder;
                        var media = "";
                        if (data[0].ContentType == "2")
                            media += $.string.Format('<div class="enbedYoutube"><embed width="420" height="345" src="{0}" type="application/x-shockwave-flash"></embed></div>', data[0].MediaUrl);


                        var question = $.string.Format('<li id="question_{0}" class="question" question="{0}" type="{3}" ZOrder="{4}" MaxResponseCount="{5}"><span class="project-question-symbol">Q.</span><span class="project-question-content">{1}. {2}</span>{6}</li>', data[0].ID, data[0].Code, data[0].QuestionText, data[0].Type, data[0].ZOrder, data[0].MaxResponseCount, media);

                        $("#listQuestion").append(question);

                        thisObj.GetListOption(data[0], dataPost);
                        $("#question_" + data[0].ID).show();
                    }
                }
                else {
                    if (data[0].DependentID == '0') {
                        $("#question_" + thisObj.CurrSentence).show();
                        thisObj.CurrentZOrder = data[0].ZOrder;
                    }
                    else {
                        var DependentResult = Axis.View.Project.Questionare.GetValueQuestion(data[0].ID);
                        $($.string.Format('#question_{0} >ul', data[0].ID)).remove();
                        thisObj.GetListOption(data[0], dataPost);
                        thisObj.CurrSentence = data[0].ID;
                        $("#question_" + data[0].ID).show();
                        thisObj.CurrentZOrder = data[0].ZOrder;
                        $.each(DependentResult.toString().split(','), function (index, item) {
                            window.setTimeout(function () {
                                $($.string.Format('input[question="{0}"][value="{1}"]', data[0].ID, item)).attr("checked", "checked");
                            }, 500);
                        });

                    }

                }
                overlay.Hide();
            },
            beforeSend: function (jqXHR, settings) {
                //
                overlay.Show();
                $(".question").hide();

            },
            error: function (jqXHR, textStatus, errorThrown) {
                overlay.Hide();
            },
            complete: function (XMLHttpRequest, textStatus) {
                overlay.Hide();
            }
        });
    },
    GetValueQuestion: function (QuesID) {
        var item = $.string.Format("#question_{0}", QuesID);
        var questionType = parseInt($(item).attr('type'));
        var ResponseValue = "";
        switch (questionType) {
            case 0: //SA
            case 2: //True/False
            case 4: //Scale
                $.each($($.string.Format('input:radio[question="{0}"]:checked', QuesID)), function (index, item) {
                    ResponseValue += $(this).val() + ',';
                });
                if (ResponseValue.length > 0)
                    ResponseValue = ResponseValue.substr(0, ResponseValue.length - 1);
                break;
            case 1: //Checkbox
            case 7: //Checkbox        
                $.each($($.string.Format('input:checkbox[question="{0}"]:checked', QuesID)), function (index, item) {
                    ResponseValue += $(this).val() + ',';
                });
                if (ResponseValue.length > 0)
                    ResponseValue = ResponseValue.substr(0, ResponseValue.length - 1);
                break;
        }

        return ResponseValue;
    },
    GetListOption: function (objData, objExtend) {
        var thisObj = Axis.View.Project.Questionare;
        thisObj.IndexQues = objData.ZOrder;
        //   var pData = '{' + $.string.Format('"QuestionID":{0}, Result:{1}', objData.ID ) + '}';
        var dataPost = $.string.Format('<InputValue UserID="0" QuestionnaireID="{0}" />', objData.ID);
        if (objExtend == undefined)
            dataPost += thisObj.ResultFinishedQuestion();
        else
            dataPost += objExtend;
        var pData = '{' + $.string.Format("'input':'{0}'", dataPost) + '}';


        $.ajax({
            url: 'Service/ProjectService.asmx/GeResponseOptionByQuestionID2',
            type: 'POST',
            data: pData,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                var data = eval("(" + pData.d + ")");
                if (data) {
                    thisObj.ShowListOptionByQuestionID(objData, data);
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    ShowListOptionByQuestionID: function (objQues, objListRes) {
        var objThis = Axis.View.Project.Questionare;
        var type = parseInt(objQues.Type + '');
        var ulQuestion = document.createElement('ul');
        $(ulQuestion).attr('id', 'ulQuestion' + objQues.ID);
        $($.string.Format('#question_{0}', objQues.ID)).append(ulQuestion);
        switch (type) {
            case 0:
                //SA
            case 1:
                //MA
            case 2:
            case 7:
                //True/Flase   
                $(ulQuestion).addClass('project-question-list-sub');
                $.each(objListRes, function (index, item) {
                    $(ulQuestion).append(objThis.GenarateOption(type, item.ID, item.ZOrder, item.Caption, objQues, item));
                    objThis.IndexRow = item.ID;
                });
                break;

            case 8:
                $(ulQuestion).addClass('project-question-list-sub');
                $.each(objListRes, function (index, item) {
                    $(ulQuestion).append(objThis.GenarateOption(8, item.ID, item.ZOrder, item.Caption, objQues, item));
                    objThis.IndexRow = item.ID;
                });
                break;

            case 3:
                $(ulQuestion).addClass('project-question-list-sub');
                $(ulQuestion).append(objThis.GenarateOption(type, '', '', '', objQues));
                break;

            case 4:
                $(ulQuestion).addClass('project-question-matrix');
                $(ulQuestion).append(objThis.GenarateOption(type, '', '', '', objQues));
                break;
            case 5:
            case 9:
            case 10:
                $(ulQuestion).addClass('project-question-matrix');
                objThis.GenarateOption(type, '', '', '', objQues, objListRes);
                break;
            case 6:
                //Arrangements   
                $(ulQuestion).addClass('project-question-list-sub');
                $.each(objListRes, function (index, item) {
                    $(ulQuestion).append(objThis.GenarateOption(type, item.ID, item.ZOrder, item.Caption, objQues, item));
                    objThis.IndexRow = item.ID;
                });


                $($.string.Format("#question_{0} > ul >li > input[type='checkbox']", objQues.ID)).bind('change', function () {
                    var liQues = $($.string.Format("#question_{0}", objQues.ID));
                    var listOrder = liQues.attr('listOrder');
                    if (typeof listOrder == 'undefined')
                        listOrder = '';
                    var qvalue = $(this).attr('qvalue');
                    var currentMax = liQues.attr('currentMax');
                    if (typeof currentMax == 'undefined')
                        currentMax = '';
                    if ($(this).is(':checked')) {
                        var Max = 1;
                        if (currentMax != "")
                            Max = parseInt(currentMax) + 1;
                        liQues.attr('currentMax', Max);
                        $(this).attr('Arrangements', Max);
                        liQues.attr('listOrder', listOrder + qvalue + '|');
                        $(this).parent().append($.string.Format('<label class="project-question-text Arrangement">{0}</label>', Max));
                    }
                    else {
                        listOrder = listOrder.replace(qvalue + '|', '');
                        liQues.attr('listOrder', listOrder);
                        Max = parseInt(currentMax) - 1;
                        liQues.attr('currentMax', Max);
                        $(this).next().next().next().remove();
                        var arrList = listOrder.split('|');
                        for (var i = 0; i < arrList.length; i++) {
                            var item = $($.string.Format("#question_{0} > ul >li > input[qvalue='{1}']", objQues.ID, arrList[i]));
                            //  if ($(item).is(':checked')) {
                            item.next().next().next().remove();
                            item.parent().append($.string.Format('<label class="project-question-text Arrangement">{0}</label>', i + 1));
                            $(item).attr('Arrangements', i + 1);
                            //}
                        }


                    }

                });
                break;
        }
    },
    GenarateOption: function (pType, ID, value, text, Question, objListRes) {
        var objThis = Axis.View.Project.Questionare;
        var index = objThis.ID++;
        var pattern = "";
        var AllowInputText = '';
        switch (pType) {
            case 0:
                //SA 
            case 2:

                var li = document.createElement('li');
                var rad = document.createElement('input');
                $(rad).attr("type", "radio");
                $(rad).attr("AllowInput", objListRes.AllowInputText);
                $(rad).attr("id", 'txtOption' + ID + '_' + Question.ID);
                $(rad).attr("textboxid", 'txt_rad_' + ID);
                $(rad).attr("name", 'rad_' + Question.ID);
                $(rad).attr("question", Question.ID);
                $(rad).attr("class", 'regular-radio big-radio');
                $(rad).attr("value", objListRes.Value);
                $(rad).attr("text", text);
                $(rad).attr("qValue", ID);
                $(li).append($(rad));
                var lable1 = document.createElement('label');
                $(lable1).attr("for", 'txtOption' + ID + '_' + Question.ID);
                $(li).append($(lable1));
                var lable2 = document.createElement('label');
                $(lable2).attr("for", 'txtOption' + ID + '_' + Question.ID);
                $(lable2).attr("class", 'project-question-text');
                if (Question.ContentType == "1")
                    $(lable2).append($.string.Format('<div class="enbedYoutube"><img src="{0}" style=" width:200px; height:200px" /></div>', text));
                else
                    $(lable2).append(text);
                $(li).append($(lable2));
                if (objListRes.AllowInputText == "1") {
                    var input = document.createElement('input');
                    $(input).attr("text", text);
                    $(input).attr("id", 'txt_rad_' + ID);
                    $(input).attr("question", 'open_' + Question.ID + '_' + value);
                    $(input).attr("class", 'regular-textbox big-textbox textbox-other');
                    $(li).append($(input));
                }
                return $(li);

            case 1:
            case 7:
                //MA
                if (objListRes.AllowInputText == "1")
                    AllowInputText = '<input type="text" id="txt_chk_{0}_{2}" class="regular-textbox big-textbox textbox-other" question="open_{2}_{1}"/>';
                pattern = '<li><input type="checkbox" AllowInput="{4}" exclusion="{6}" id="txtOption{0}_{2}" textboxid="txt_chk_{0}_{2}" name="rad_{2}" text="{3}" question="{2}" class="regular-checkbox big-checkbox"  value="{5}" qValue="{0}"/>'
                        + '<label for="txtOption{0}_{2}"></label>'
                        + '<label for="txtOption{0}_{2}" class="project-question-text">'
                        + '{3}</label>'
                        + AllowInputText + '</li>';

                if (Question.ContentType == "1") {
                    var image = $.string.Format('<div class="enbedYoutube"><img src="{0}" style=" width:200px; height:200px" /></div>', text);
                    pattern = '<li><input type="checkbox" AllowInput="{4}" exclusion="{6}" id="txtOption{0}_{2}" textboxid="txt_chk_{0}_{2}" name="rad_{2}" text="{3}" question="{2}" class="regular-checkbox big-checkbox"  value="{5}" qValue="{0}"/>'
                        + '<label for="txtOption{0}_{2}"></label>'
                        + '<label for="txtOption{0}_{2}" class="project-question-text">'
                        + '{7}</label>'
                        + AllowInputText + '</li>';
                    return $.string.Format(pattern, ID, value, Question.ID, text, objListRes.AllowInputText, objListRes.Value, objListRes.Type, image);
                }
                else
                    return $.string.Format(pattern, ID, value, Question.ID, text, objListRes.AllowInputText, objListRes.Value, objListRes.Type);
            case 3:
                //text
                return ' <li>'
                                + '<input type="text" class="scale-textbox" id="txtOption' + Question.ID + '"/>'
                            + '</li>';
            case 6:
                //Arrance
                if (objListRes.AllowInputText == "1")
                    AllowInputText = '<input type="text" id="txt_chk_{0}_{2}" class="regular-textbox big-textbox textbox-other" question="open_{2}_{1}"/>';
                pattern = '<li><input type="checkbox" AllowInput="{4}" id="txtOption{0}_{2}" textboxid="txt_chk_{0}_{2}" name="rad_{2}" text="{3}" question="{2}" class="regular-checkbox big-checkbox"  value="{5}" qValue="{0}"/>'
                        + '<label for="txtOption{0}_{2}"></label>'
                        + '<label for="txtOption{0}_{2}" class="project-question-text">'
                        + '{3}</label>'
                        + AllowInputText + '</li>';
                return $.string.Format(pattern, ID, value, Question.ID, text, objListRes.AllowInputText, objListRes.Value);
            case 4:
                //Scale
                // var Scale = $.string.Format('<li>{0}</li>', Question.ScaleFromText);
                var ScaleFrom = parseInt(Question.ScaleFrom + '');
                var ScaleTo = parseInt(Question.ScaleTo + '');
                var scalePattern = '<li> <input type="radio" id="txtOption{0}" name="rad_matrix{1}" question="{1}" class="regular-radio big-radio" value="{0}" />'
                                    + '<label for="txtOption{0}"></label>'
                                    + '</li>';
                Scale = ' <li class="newline"></li>'
                Scale += ' <li>&nbsp;</li>'
                for (var i = ScaleFrom; i <= ScaleTo; i++)
                    Scale += $.string.Format('<li>{0}</li>', i);

                Scale += '<li class="newline">{0}</li>';
                Scale += $.string.Format('<li>{0}</li>', Question.ScaleFromText);
                for (var i = ScaleFrom; i <= ScaleTo; i++)
                    Scale += $.string.Format(scalePattern, i, Question.ID);
                Scale += $.string.Format('<li>{0}</li>', Question.ScaleToText);
                return Scale;
            case 5:
                var matrix = "";
                var thisObj = Axis.View.Project.Questionare;
                var pData = '{' + $.string.Format('"QuestionID":{0},"ProjectID":{1}', Question.ID, ProjectID) + '}';
                $.ajax({
                    url: 'Service/ProjectService.asmx/GetQuestionListID',
                    type: 'POST',
                    data: pData,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (pData, textStatus, jqXHR) {
                        var data = eval("(" + pData.d + ")");
                        matrix += '<li class="newline"></li>';
                        matrix += '<li>&nbsp;</li>';
                        $.each(objListRes, function (i, item) {
                            // if (i > 0) {
                            var caption = "";
                            if (item != undefined)
                                caption = item.Caption;
                            matrix += $.string.Format('<li style="clear: none">{0}</li>', caption);
                            //};
                        });
                        var pattern = '<li style="clear: none">'
                                + '<input type="radio" id="txtOption{2}" name="rad_matrix{1}" class="regular-radio big-radio" value="{5}" Matrix="{3}" Row="{4}" />'
                                + '<label for="txtOption{2}"></label>'
                            + '</li>';

                        $("#question_" + Question.ID).attr('numRow', data.length - 1);
                        $.each(data, function (i, item) {
                            if (i > 0) {
                                matrix += '<li class="newline"></li>';
                                matrix += $.string.Format('<li>{0}</li>', item.QuestionText);
                                $.each(objListRes, function (j, item2) {
                                    matrix += $.string.Format(pattern, item.ID, i + 1, +i + "_" + j + "_" + Question.ID, Question.ID, item.ID, j + 1);

                                });
                            }

                        });
                        $("#ulQuestion" + Question.ID).append(matrix);

                        $.each(UserResponse, function (index, item) {
                            if (item.ParentQuestionnaireID == Question.ID) {
                                $($.string.Format('input:radio[row="{0}"][value="{1}"]', item.QuestionnaireID, item.ResponseValue)).attr("checked", "checked");
                            }

                        });

                        $($.string.Format("#ulQuestion{0} li", Question.ID)).width(400 / (objListRes.length));

                    },
                    beforeSend: function (jqXHR, settings) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    }
                });

                break;

            case 8:
                //MA

                /*
                return ' <li>'
                + '<input type="text" class="scale-textbox" id="txtOption' + Question.ID + '"/>'
                + '</li>';
                */
                pattern = '<li>'
                            + '<input type="text" class="scale-textbox checksum" question="{2}" id="txtOption{2}" qID="{0}" />'
                        + '<label for="txtOption{0}_{2}" class="project-question-text">'
                        + '{3}</label>'

                        + '</li>';
                return $.string.Format(pattern, ID, value, Question.ID, text, objListRes.AllowInputText, objListRes.Value);

            case 9:
                var matrix = "";
                var thisObj = Axis.View.Project.Questionare;
                var pData = '{' + $.string.Format('"QuestionID":{0},"ProjectID":{1}', Question.ID, ProjectID) + '}';
                $.ajax({
                    url: 'Service/ProjectService.asmx/GetQuestionListID',
                    type: 'POST',
                    data: pData,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (pData, textStatus, jqXHR) {
                        var data = eval("(" + pData.d + ")");
                        matrix += '<li class="newline"></li>';
                        matrix += '<li>&nbsp;</li>';
                        $.each(objListRes, function (i, item) {
                            //if (i > 0) {
                            var caption = "";
                            if (item != null)
                                if (typeof item != 'undefined')
                                    if (typeof item.Caption != 'undefined')
                                        caption = item.Caption;
                            matrix += $.string.Format('<li style="clear: none">{0}</li>', caption);
                            //};
                        });
                        var pattern = '<li style="clear: none">'
                                + '<input type="checkbox" id="txtOption{2}" name="rad_matrix{1}" class="regular-checkbox big-checkbox" value="{5}" Matrix="{3}" Row="{4}" />'
                                + '<label for="txtOption{2}"></label>'
                            + '</li>';

                        $("#question_" + Question.ID).attr('numRow', data.length - 1);
                        $.each(data, function (i, item2) {
                            if (i > 0) {
                                matrix += '<li class="newline"></li>';
                                matrix += $.string.Format('<li>{0}</li>', item2.QuestionText);
                                $.each(objListRes, function (j, item2) {
                                    matrix += $.string.Format(pattern, item2.ID, i + 1, +i + "_" + j + "_" + Question.ID, Question.ID, item2.ID, j + 1);

                                });
                            }

                        });
                        $("#ulQuestion" + Question.ID).append(matrix);

                        $.each(UserResponse, function (index, item) {
                            if (item.ParentQuestionnaireID == Question.ID) {
                                $($.string.Format('input:radio[row="{0}"][value="{1}"]', item.QuestionnaireID, item.ResponseValue)).attr("checked", "checked");
                            }

                        });

                        $($.string.Format("#ulQuestion{0} li", Question.ID)).width(300 / (objListRes.length));

                    },
                    beforeSend: function (jqXHR, settings) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    }
                });

                break;
            case 10:
                var matrix = "";
                var thisObj = Axis.View.Project.Questionare;
                var pData = '{' + $.string.Format('"QuestionID":{0},"ProjectID":{1}', Question.ID, ProjectID) + '}';
                $.ajax({
                    url: 'Service/ProjectService.asmx/GetQuestionListID',
                    type: 'POST',
                    data: pData,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (pData, textStatus, jqXHR) {
                        var data = eval("(" + pData.d + ")");
                        matrix += '<li class="newline"></li>';
                        matrix += '<li>&nbsp;</li>';
                        $.each(objListRes, function (i, item) {
                            // if (i > 0) {
                            var caption = "";
                            if (item != undefined)
                                caption = item.Caption;
                            matrix += $.string.Format('<li style="clear: none">{0}</li>', caption);
                            //};
                        });
                        var pattern = '<li style="clear: none">'
                                + '<input type="radio" id="txtOption{2}" name="rad_matrix{1}" class="regular-radio big-radio" value="{5}" Matrix="{3}" Row="{4}" />'
                                + '<label for="txtOption{2}"></label>'
                            + '</li>';

                        $("#question_" + Question.ID).attr('numRow', data.length - 1);
                        $.each(data, function (i, item) {
                            if (i > 0) {
                                matrix += '<li class="newline"></li>';
                                matrix += $.string.Format('<li>{0}</li>', item.QuestionText);
                                $.each(objListRes, function (j, item2) {
                                    matrix += $.string.Format(pattern, item.ID, j+1, +i + "_" + j + "_" + Question.ID, Question.ID, item.ID, j + 1);

                                });
                            }

                        });
                        $("#ulQuestion" + Question.ID).append(matrix);

                        $.each(UserResponse, function (index, item) {
                            if (item.ParentQuestionnaireID == Question.ID) {
                                $($.string.Format('input:radio[row="{0}"][value="{1}"]', item.QuestionnaireID, item.ResponseValue)).attr("checked", "checked");
                            }

                        });

                        $($.string.Format("#ulQuestion{0} li", Question.ID)).width(400 / (objListRes.length));

                    },
                    beforeSend: function (jqXHR, settings) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    }
                });

                break;
        }
    },
    SaveServey: function (IsCompleted) {
        var objThis = this;
        var data = { ProjectID: ProjectID, ProjectName: ProjectName };
        var ret = "{ResponseOption:[";
        $.each($(".question"), function (index, item) {
            var question = $(item).attr('question');
            var questionType = parseInt($(item).attr('type'));
            var ResponseValue = "";
            switch (questionType) {
                case 0: //SA
                case 2: //True/False
                case 4: //Scale
                    $.each($($.string.Format('input:radio[question="{0}"]:checked', question)), function (index, item) {
                        ret += "{";
                        ret += $.string.Format("QuestionID:'{0}',", question);
                        ret += $.string.Format("QuestionType:'{0}'", questionType);
                        ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                        var ResponseText = $(this).attr('text');
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $($.string.Format("#txt_rad_{0}_{1}", ResID, question)).val();
                            }
                        ret += $.string.Format(",ResponseText:'{0}'", ResponseText);
                        ret += "},";
                    });
                    break;
                case 1: //Checkbox        
                    $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                        ret += "{";
                        ret += $.string.Format("QuestionID:'{0}',", question);
                        ret += $.string.Format("QuestionType:'{0}'", questionType);
                        ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                        var ResponseText = $(this).attr('text');
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $($.string.Format("#txt_chk_{0}_{1}", ResID, question)).val();

                            }
                        ret += $.string.Format(",ResponseText:'{0}'", ResponseText);
                        ret += "},";
                    });
                    break;
                case 3: //Textbox       
                    ret += "{";
                    ret += $.string.Format("QuestionID:'{0}',", question);
                    ret += $.string.Format("QuestionType:'{0}'", questionType);
                    ret += $.string.Format(",ResponseValue:'{0}'", 0);
                    ret += $.string.Format(",ResponseText:'{0}'", $("#txtOption" + question).val());
                    ret += "},";
                    break;
                case 5: //Matrix
                    $.each($($.string.Format('input:radio[matrix="{0}"]:checked', question)), function (index, item) {
                        ret += "{";
                        ret += $.string.Format("QuestionID:'{0}',", $(this).attr('row'));
                        ret += $.string.Format("QuestionType:'{0}'", questionType);
                        ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                        var ResponseText = '';
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $("#txt_rad_" + ResID).val();
                            }
                        ret += $.string.Format(",ResponseText:'{0}'", ResponseText);
                        ret += "},";
                    });
                    break;
                case 9: //Matrix
                    $.each($($.string.Format('input:checkbox[matrix="{0}"]:checked', question)), function (index, item) {
                        ret += "{";
                        ret += $.string.Format("QuestionID:'{0}',", $(this).attr('row'));
                        ret += $.string.Format("QuestionType:'{0}'", questionType);
                        ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                        var ResponseText = '';
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $("#txt_rad_" + ResID).val();
                            }
                        ret += $.string.Format(",ResponseText:'{0}'", ResponseText);
                        ret += "},";
                    });
                    break;
                case 10: //Matrix
                    $.each($($.string.Format('input:radio[matrix="{0}"]:checked', question)), function (index, item) {
                        ret += "{";
                        ret += $.string.Format("QuestionID:'{0}',", $(this).attr('row'));
                        ret += $.string.Format("QuestionType:'{0}'", questionType);
                        ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                        var ResponseText = '';
                        if (typeof $(this).attr('AllowInput') != 'undefined')
                            if ($(this).attr('AllowInput') == "1") {
                                var ResID = $(this).attr('qvalue');
                                ResponseText = $("#txt_rad_" + ResID).val();
                            }
                        ret += $.string.Format(",ResponseText:'{0}'", ResponseText);
                        ret += "},";
                    });
                    break;
                case 6: //Arrangement        
                    $.each($($.string.Format('input:checkbox[question="{0}"]:checked', question)), function (index, item) {
                        ret += "{";
                        ret += $.string.Format("QuestionID:'{0}',", question);
                        ret += $.string.Format("QuestionType:'{0}'", questionType);
                        ret += $.string.Format(",ResponseValue:'{0}'", $(this).val());
                        var ResponseText = $(this).attr('Arrangements');
                        ret += $.string.Format(",ResponseText:'{0}'", ResponseText);
                        ret += "},";
                    });
                    break;
            }

        });
        if (ret != "{ResponseOption:[")
            ret = ret.substr(0, ret.length - 1);
        ret += "]}";

        data.Action = 'INSERT';
        data.ResponseOption = ret;
        data.IsCompleted = IsCompleted;
        $.Ajax({
            url: 'Service/ServeyService.ashx',
            type: 'POST',
            data: data,
            success: function (pData, textStatus, jqXHR) {
                if (pData) {
                    var data = eval("(" + pData + ")");
                    var pContent = "Bạn đã hoàn thành xong khảo sát của dự án này";
                    if (IsCompleted == 0) {
                        pContent = "Hệ thống đã ghi nhận kết quả của bạn ở giai đoạn này.Hy vọng bạn sớm quay lại làm tiếp dự án này";
                        $.CAlert.Alert({
                            Title: "Lưu kết quả",
                            Content: pContent
                        });
                    }
                    if (data.IsSuccessfull, IsCompleted) {
                        objThis.ShowMessageCompleteProject(data);
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    ShowMessageCompleteProject: function (message, IsCompleted) {
        var pContent = message.Description;
        //        switch (message.Code) {
        //            case "USER_RESPONSE_LOTTERYCODE":
        //                pContent = $.string.Format("Chúc mừng bạn đã hoàn thành xong khảo sát. Mã số rút thăm của bạn là {0}", message.Result);
        //                break;
        //            case "USER_RESPONSE_GIFT":
        //                pContent = $.string.Format("Chúc mừng bạn đã hoàn thành xong khảo sát. Mời bạn đến thăm hồ sơ thành viên của mình để xem quà", message.Result);
        //                break;
        //            case "USER_RESPONSE_MARK":
        //                pContent = $.string.Format("Chúc mừng bạn đã hoàn thành xong khảo sát. Bạn đã được cộng {0} vào tài khoản. Mời bạn đến thăm hồ sơ thành viên của mình để xem tổng điểm.", message.Result);
        //                break;
        //            default:
        //                pContent = $.string.Format("Chúc mừng bạn đã hoàn thành xong khảo sát. Mời bạn đến thăm hồ sơ thành viên của mình để xem quà", message.Result);
        //        }
        $.CAlert.Confirm({
            Title: "Lưu kết quả",
            Content: pContent
        }, function () {
            window.location = "ProjectList.aspx";
        });
    },
    EventOptionOrther: function () {
        $("input:checkbox.checkbox-other").live('change', function () {
            if ($(this).is(":checked")) {
                $(textboxid).show();
            }
            else {
                $(textboxid).hide();
            }
        });
        $('input[name^=rad_]').live('change', function () {
            var textboxid = $(this).attr("textboxid") || "";
            var question = $(this).attr('question');
            if (textboxid) {
                $("#" + textboxid).show();

                // $('input[question="' + question + '"]').attr("has_textboxid", textboxid);
            }
            else {
                textboxid = $(this).attr("has_textboxid") || "";
                if (textboxid)
                    $("#" + textboxid).hide();
            }
        });
    },
    CheckUnFinished: function () {
        var thisObj = Axis.View.Project.Questionare;

        if (LastOutputValue == "1") {
            $.CAlert.Alert({
                Title: "Thông báo",
                Content: LastOutputDescription
            }, function () {
                window.location = "ProjectList.aspx";
            });
        }
        else {
            $.each(UserResponse, function (index, item) {
                var flag = -1;
                if (item.ParentQuestionnaireID == 0) {
                    for (var i = 0; i < thisObj.FinishedQuestion.length; i++) {
                        if (thisObj.FinishedQuestion[i].ID == item.QuestionnaireID)
                            flag = i;
                    }
                    if (flag == -1) {
                        item.ID = item.QuestionnaireID;
                        thisObj.FinishedQuestion.push(item);
                    }
                }
                else// matrix
                {
                    for (var i = 0; i < thisObj.FinishedQuestion.length; i++) {
                        if (thisObj.FinishedQuestion[i].ID == item.ParentQuestionnaireID)
                            flag = i;
                    }
                    if (flag == -1) {
                        thisObj.FinishedQuestion.push({ ID: item.ParentQuestionnaireID });
                    }
                }

            });
            if (thisObj.FinishedQuestion.length == 0)// chua tra loi cau nao
                thisObj.GetNextQuestion();
            else {
                $("#QuestionContent").show();
                $("#Panel-ProfileForProject").hide();
                thisObj.LoadQuestionAnswered();
                setTimeout(function () {
                    thisObj.SetAnswer();
                }, 500);
            }
        }
    },
    LoadQuestionAnswered: function () {
        var thisObj = Axis.View.Project.Questionare;
        while (1) {
            if (thisObj.FinishedQuestion.length == 0) {
                // thisObj.SetAnswer();// Axis.View.Project.Questionare.SetAnswer()
                return;
            }
            var QuesID = thisObj.FinishedQuestion[0].ID;
            thisObj.FinishedQuestion.splice(0, 1);
            thisObj.CurrSentence = QuesID;
            //            console.log('thisObj.FinishedQuestion', thisObj.FinishedQuestion[0]);
            //            thisObj.IndexQues = thisObj.FinishedQuestion[0].ZOrder;
            var pData = '{' + $.string.Format('"QuestionID":{0},"ProjectID":{1}', QuesID, ProjectID) + '}';
            $.ajax({
                url: 'Service/ProjectService.asmx/GetQuestionListID',
                type: 'POST',
                data: pData,
                cache: false,
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (pData, textStatus, jqXHR) {
                    var data = eval("(" + pData.d + ")");
                    if (data.length > 0) {
                        var question = $.string.Format('<li id="question_{0}" class="question" question="{0}" type="{3}" MaxResponseCount="{4}"><span class="project-question-symbol">Q.</span><span>{1}. {2}?</span></li>', data[0].ID, data[0].ZOrder, data[0].QuestionText, data[0].Type, data[0].MaxResponseCount);
                        $("#listQuestion").append(question);
                        thisObj.GetListOption(data[0]);
                        $("#question_" + QuesID).show();
                        thisObj.Path.push(data[0]);
                    }
                    thisObj.LoadQuestionAnswered();

                },
                beforeSend: function (jqXHR, settings) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                },
                complete: function (XMLHttpRequest, textStatus) {
                }
            });
        }
    },
    SetAnswer: function () {
        var thisObj = Axis.View.Project.Questionare;
        for (var i = 0; i < thisObj.Path.length; i++) {
            $(".question").hide();
            $.each(UserResponse, function (index, item) {
                if (thisObj.Path[i].ID == item.QuestionnaireID) {

                    //AllowInputText
                    switch (thisObj.Path[i].Type) {
                        case 0:
                        case 1:
                        case 2:
                        case 4:
                            $($.string.Format('input[question="{0}"][value="{1}"]', thisObj.Path[i].ID, item.ResponseValue)).attr("checked", "checked");
                            if (item.AllowInputText == "1") {
                                $($.string.Format('input[question="open_{0}_{1}"]', item.QuestionnaireID, item.ResponseValue)).show().val(item.ResponseText);
                            }
                            break;
                        case 3:
                            $("#txtOption" + item.QuestionnaireID).val(item.ResponseText);
                            break;
                    }
                }
            });
            $("#btnBackQuestion").show();
            thisObj.CurrSentence = thisObj.Path[i].ID;
            $("#question_" + thisObj.Path[i].ID).show();
        }

        thisObj.IndexQues = thisObj.Path.length;
    },
    Init: function () {
        var thisObj = Axis.View.Project.Questionare;
        thisObj.InputValue = $.string.Format('<InputValue ProjectID="{0}" Context="NextQuestion" />', ProjectID);
        thisObj.CheckUnFinished();
        thisObj.EventOptionOrther();

    }
}
$(function () {
    if (_SYS_GLOBAL != undefined)
        if (_SYS_GLOBAL.MEMBER.ID == '0')
            return;
    Axis.View.Project.Questionare.Init();
});
function NextQuestion() {
    var thisObj = Axis.View.Project.Questionare;
    thisObj.GetNextQuestion();
}
function SaveServey() {
    var thisObj = Axis.View.Project.Questionare;
    thisObj.SaveServey(0);
}
function BackQuestion() {
    var thisObj = Axis.View.Project.Questionare;
    thisObj.BackQuestion(0);
}

